package com.datasentinel.util;

import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HashUtils  
{
	/*
	 * Possible algorithm names:
	 * 
	 * MD2    
	 * MD5
	 * SHA-1 
	 * SHA-256 
	 * SHA-384 
	 * SHA-512
	 *  
	 */
	
	protected static final Logger logger = Logger.getLogger(HashUtils.class.getName());

	private static final String MESSAGE_DIGEST_ALGORITHM_NAME="SHA-256";
	
	private static DigestUtils digestUtils;
	
	static
	{
		try
		{
			digestUtils = new DigestUtils(MESSAGE_DIGEST_ALGORITHM_NAME);
		}
		catch (NoSuchAlgorithmException e)
		{
			logger.log(Level.SEVERE, "Unable to initialize digesting", e);
		}	
	}

	
	public static long getStringHashedToLong(String value)
	{
		synchronized(digestUtils)
		{
			return digestUtils.sum(value.getBytes()).longValue();
		}
	}

	public static long getLongHashedToLong(long value)
	{
		return getStringHashedToLong(Long.toString(value));
	}

	public static String getLongHashedToString(long value)
	{
		return Long.toString(getLongHashedToLong(value));
	}

	public static String getStringHashedToString(String value)
	{
		return Long.toString(getStringHashedToLong(value));
	}
	
	public static String getStringHashedDerivative(String value, int maxLength)
	{
		if(StringHelper.isEmpty(value))
		{
			return "";
		}
		
		String hash = "";
		synchronized(digestUtils)
		{
			hash = digestUtils.sum(value.getBytes()).toString(Character.MAX_RADIX);
		}
		
		if(hash.length() > maxLength)
		{
			hash = hash.substring(0, maxLength);
		}
		
		return hash;
	}

}
